package projetsia.com.hairhunter;

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;


import com.google.android.gms.internal.ma;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import com.google.android.gms.maps.CameraUpdateFactory;
import android.location.LocationListener;
import android.location.LocationManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.PopupMenu;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.widget.PopupMenu.OnMenuItemClickListener;

public class MainActivity extends Activity implements LocationListener {

    private GoogleMap gMap; // Might be null if Google Play services APK is not available.
    private Marker marker;
    private LocationManager locationManager;
    private GetSalonnTask mSalonTask;
    private HashMap<String, String> idTab;
    String userId;
    String idMap;
    private AddToFavorisTask mAddFavTask = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bundle objetbunble = this.getIntent().getExtras();
        // récupération de la valeur
        userId= objetbunble .getString("userId");

        mSalonTask = new GetSalonnTask();
        mSalonTask.execute();
     //   setUpMapIfNeeded();








    }

    @Override
    protected void onResume() {
        super.onResume();
     //   setUpMapIfNeeded();
        //Obtention de la référence du service
        locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);

        //Si le GPS est disponible, on s'y abonne
        if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            abonnementGPS();
        }
    }





    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #gMap} is not null.
     * <p>
     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     * <p>
     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
     * have been completely destroyed during this process (it is likely that it would only be
     * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
     * method in {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (gMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            gMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (gMap != null) {
             //   setUpMap();

                //gMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
                //marker =
                      //  gMap.addMarker(new MarkerOptions().title("Vous êtes ici").position(new LatLng(0, 0)));
                gMap.addMarker(new MarkerOptions()
                        .position(new LatLng(48.8620722, 2.352047))
                        .alpha(0.7f).title("Salon paris 1").snippet("1 places libre")
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
                gMap.addMarker(new MarkerOptions()
                        .position(new LatLng(48.8320727, 2.352047))
                        .alpha(1.5f).title("Salon paris 2").snippet("3 places libre")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
                gMap.addMarker(new MarkerOptions()
                        .position(new LatLng(48.8120727, 2.352047))
                        .alpha(1.5f).title("Salon paris 3").snippet("10 places libre")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));

                gMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
                gMap.setMyLocationEnabled(true);

            }
        }
    }

    public class GetSalonnTask extends AsyncTask<String, Void, String> {


        GetSalonnTask() {
        }

        @Override
        protected String doInBackground(String... params) {

            HttpClient httpClient = new DefaultHttpClient();

            // In a POST request, we don't pass the values in the URL.
            //Therefore we use only the web page URL as the parameter of the HttpPost argument
            HttpPost httpPost = new HttpPost("http://hairhunter.kilu.de/index.php");

            BasicNameValuePair tagBasicNameValuePAir = new BasicNameValuePair("tag", "salonList");

            // We add the content that we want to pass with the POST request to as name-value pairs
            //Now we put those sending details to an ArrayList with type safe of NameValuePair
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
            nameValuePairList.add(tagBasicNameValuePAir);

            try {
                // UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs.
                //This is typically useful while sending an HTTP POST request.
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);

                // setEntity() hands the entity (here it is urlEncodedFormEntity) to the request.
                httpPost.setEntity(urlEncodedFormEntity);

                try {
                    // HttpResponse is an interface just like HttpPost.
                    //Therefore we can't initialize them
                    HttpResponse httpResponse = httpClient.execute(httpPost);

                    // According to the JAVA API, InputStream constructor do nothing.
                    //So we can't initialize InputStream although it is not an interface
                    InputStream inputStream = httpResponse.getEntity().getContent();

                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                    StringBuilder stringBuilder = new StringBuilder();

                    String bufferedStrChunk = null;

                    while((bufferedStrChunk = bufferedReader.readLine()) != null){
                        stringBuilder.append(bufferedStrChunk);
                    }

                    return stringBuilder.toString();

                } catch (ClientProtocolException cpe) {
                    System.out.println("First Exception caz of HttpResponese :" + cpe);
                    cpe.printStackTrace();
                } catch (IOException ioe) {
                    System.out.println("Second Exception caz of HttpResponse :" + ioe);
                    ioe.printStackTrace();
                }

            } catch (UnsupportedEncodingException uee) {
                System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
                uee.printStackTrace();
            }

            return null;
        }


        @Override
        protected void onPostExecute(String result) {
            mSalonTask = null;


            super.onPostExecute(result);

            try {

                JSONObject jObj = new JSONObject(result);

                System.out.println(result);
                if (jObj.getString("success") != null) {
                    String res = jObj.getString("success");

                    /********************************************/
            /* Si il vaut 1, l'utilisateur est connecté */
                    /********************************************/

                    if (Integer.parseInt(res) == 1) {
                        int salonLength = Integer.parseInt(jObj.getString("taille"));
                        idTab = new HashMap<String, String>();

                        if (gMap == null) {
                            // Try to obtain the map from the SupportMapFragment.
                            gMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
                                    .getMap();
                        for (int i = 0; i < salonLength; i++) {

                            JSONObject salonInfo = jObj.getJSONObject(String.valueOf(i));
                            JSONObject salonInfo2 = salonInfo.getJSONObject("salonList");
                            String salonId = salonInfo2.getString("id");
                            String salonName = salonInfo2.getString("nom");
                            String salonLongitude = salonInfo2.getString("longitude");
                            String salonLatitude = salonInfo2.getString("latitude");


                            // Check if we were successful in obtaining the map.
                            if (gMap != null) {
                                //   setUpMap();

                                //gMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
                                //marker =
                                //  gMap.addMarker(new MarkerOptions().title("Vous êtes ici").position(new LatLng(0, 0)));
                                marker = gMap.addMarker(new MarkerOptions()
                                        .position(new LatLng(Double.valueOf(salonLongitude), Double.valueOf(salonLatitude)))
                                        .alpha(0.7f).title(salonName).snippet("1 places libre")
                                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)
                                        )

                                );

                                idTab.put(marker.getId(), salonId);


                            }


                            System.out.println(" JsonObject " + i + " " + salonInfo);
                        }
                    }
                        gMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
                        gMap.setMyLocationEnabled(true);


                        gMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                            @Override
                            public boolean onMarkerClick(Marker marker) {

                               idMap = idTab.get(marker.getId());

                                openOptionsMenu();




                            //    Toast.makeText(getApplicationContext(), "Marqueur cliqué "+idTab.get(marker.getId()), Toast.LENGTH_LONG).show();

                                return false;
                            }
                        });



                    }else{
                        Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        /*    if(result["success"] == 1){
                    Toast.makeText(getApplicationContext(), "HTTP POST is working...", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(getApplicationContext(), "Invalid POST req...", Toast.LENGTH_LONG).show();
                }*/
        }

        @Override
        protected void onCancelled() {
            mSalonTask = null;
        //    showProgress(false);
        }

    }



    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     * <p>
     * This should only be called once and when we are sure that {@link #gMap} is not null.
     */
    private void setUpMap() {
        gMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));

    }


    /**
     * {@inheritDoc}
     */
    @Override
    public void onPause() {
        super.onPause();

        //On appelle la méthode pour se désabonner
        desabonnementGPS();
    }

    /**
     * Méthode permettant de s'abonner à la localisation par GPS.
     */
    public void abonnementGPS() {
        //On s'abonne
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10,  this);
    }

    /**
     * Méthode permettant de se désabonner de la localisation par GPS.
     */
    public void desabonnementGPS() {
        //Si le GPS est disponible, on s'y abonne
        locationManager.removeUpdates(this);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onLocationChanged(final Location location) {
        //On affiche dans un Toat la nouvelle Localisation
        final StringBuilder msg = new StringBuilder("lat : ");
        msg.append(location.getLatitude());
        msg.append( "; lng : ");
        msg.append(location.getLongitude());

        Toast.makeText(this, msg.toString(), Toast.LENGTH_SHORT).show();

        //Mise à jour des coordonnées
        final LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
        marker.setPosition(latLng);
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.create_salon_activity, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(item.getItemId() == R.id.action_reservation){

            Toast.makeText(getApplicationContext(), "Reservation", Toast.LENGTH_LONG).show();
        }
        else if(item.getItemId() == R.id.action_comment){

            Intent dashboard = new Intent(getApplicationContext(), NoteActivity.class);

            Bundle objetbunble1 = new Bundle();
            objetbunble1.putString("idSalon", idMap);
            objetbunble1.putString("userId",userId);
            // on passe notre objet a notre activities
            dashboard.putExtras(objetbunble1);

            dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(dashboard);

        }else if(item.getItemId() == R.id.action_favoris){

            mAddFavTask = new AddToFavorisTask(idMap, userId);
            mAddFavTask.execute(idMap, userId);
       //     Toast.makeText(getApplicationContext(), "Favoris "+idMap, Toast.LENGTH_LONG).show();

        }else if(item.getItemId() == R.id.show_favoris){

            Intent dashboard = new Intent(getApplicationContext(), FavorisListActivity.class);

            Bundle objetbunble1 = new Bundle();
            objetbunble1.putString("userId",userId);
            // on passe notre objet a notre activities
            dashboard.putExtras(objetbunble1);

            dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(dashboard);

        }


        return super.onOptionsItemSelected(item);
    }

    /**
     * {@inheritDoc}
     */

    public void onProviderDisabled(final String provider) {
        //Si le GPS est désactivé on se désabonne
        if("gps".equals(provider)) {
            desabonnementGPS();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onProviderEnabled(final String provider) {
        //Si le GPS est activé on s'abonne
        if("gps".equals(provider)) {
            abonnementGPS();
        }
    }





    /**
     * {@inheritDoc}
     */
    @Override
    public void onStatusChanged(final String provider, final int status, final Bundle extras) { }



    public class AddToFavorisTask extends AsyncTask<String, Void, String> {

        private final String mIdSalon;
        private final String mIdUser;

        AddToFavorisTask(String idSalon, String idUser) {
            mIdSalon = idSalon;
            mIdUser = idUser;


        }

        @Override
        protected String doInBackground(String... params) {

            String paramIdSalon = params[0];
            String paramIdUser = params[1];


            HttpClient httpClient = new DefaultHttpClient();

            // In a POST request, we don't pass the values in the URL.
            //Therefore we use only the web page URL as the parameter of the HttpPost argument
            HttpPost httpPost = new HttpPost("http://hairhunter.kilu.de/index.php");

            // Because we are not passing values over the URL, we should have a mechanism to pass the values that can be
            //uniquely separate by the other end.
            //To achieve that we use BasicNameValuePair
            //Things we need to pass with the POST request
            BasicNameValuePair idSalonBasicNameValuePair = new BasicNameValuePair("paramIdSalon", paramIdSalon);
            BasicNameValuePair idUserBasicNameValuePAir = new BasicNameValuePair("paramIdUser", paramIdUser);

            System.out.println(idSalonBasicNameValuePair+" ---- "+idUserBasicNameValuePAir);

            BasicNameValuePair tagBasicNameValuePAir = new BasicNameValuePair("tag", "addFavoris");

            // We add the content that we want to pass with the POST request to as name-value pairs
            //Now we put those sending details to an ArrayList with type safe of NameValuePair
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
            nameValuePairList.add(idSalonBasicNameValuePair);
            nameValuePairList.add(idUserBasicNameValuePAir);

            nameValuePairList.add(tagBasicNameValuePAir);


            try {
                // UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs.
                //This is typically useful while sending an HTTP POST request.
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);

                // setEntity() hands the entity (here it is urlEncodedFormEntity) to the request.
                httpPost.setEntity(urlEncodedFormEntity);

                try {
                    // HttpResponse is an interface just like HttpPost.
                    //Therefore we can't initialize them
                    HttpResponse httpResponse = httpClient.execute(httpPost);

                    // According to the JAVA API, InputStream constructor do nothing.
                    //So we can't initialize InputStream although it is not an interface
                    InputStream inputStream = httpResponse.getEntity().getContent();

                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                    StringBuilder stringBuilder = new StringBuilder();

                    String bufferedStrChunk = null;

                    while((bufferedStrChunk = bufferedReader.readLine()) != null){
                        stringBuilder.append(bufferedStrChunk);
                    }

                    return stringBuilder.toString();

                } catch (ClientProtocolException cpe) {
                    System.out.println("First Exception caz of HttpResponese :" + cpe);
                    cpe.printStackTrace();
                } catch (IOException ioe) {
                    System.out.println("Second Exception caz of HttpResponse :" + ioe);
                    ioe.printStackTrace();
                }

            } catch (UnsupportedEncodingException uee) {
                System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
                uee.printStackTrace();
            }

            return null;
        }


        @Override
        protected void onPostExecute(String result) {
            mAddFavTask = null;
        //    showProgress(false);

            super.onPostExecute(result);

            try {
                JSONObject jObj = new JSONObject(result);

                System.out.println(result);
                if (jObj.getString("success") != null) {
                    String res = jObj.getString("success");

                    /********************************************/
            /* Si il vaut 1, l'utilisateur est connecté */
                    /********************************************/

                    if (Integer.parseInt(res) == 1) {

                        Toast.makeText(getApplicationContext(), "Succès", Toast.LENGTH_LONG).show();

                    /*    Intent dashboard = new Intent(getApplicationContext(), LoginActivity.class);
                        dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(dashboard);  */


                        /****************************/
              /* Ferme l'Activity "Login" */
                        /****************************/

                        //finish();
                    }else{
                        Toast.makeText(getApplicationContext(), res, Toast.LENGTH_LONG).show();
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        /*    if(result["success"] == 1){
                    Toast.makeText(getApplicationContext(), "HTTP POST is working...", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(getApplicationContext(), "Invalid POST req...", Toast.LENGTH_LONG).show();
                }*/
        }

        @Override
        protected void onCancelled() {
            mAddFavTask = null;
          //  showProgress(false);
        }

    }




}
